package cn.bgs.controller;


import cn.bgs.common.R;
import cn.bgs.pojo.User;
import cn.bgs.service.IUserService;
import cn.bgs.utils.EmailUtil;
import cn.bgs.utils.RedisUtil;
import cn.bgs.vo.Residents;
import cn.bgs.vo.UserFile;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.bgs.common.MD5;
import cn.bgs.common.R;
import cn.bgs.service.IUserService;
import cn.bgs.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * <p>
 * 用户/管理员表 前端控制器
 * </p>
 *
 * @author cf
 * @since 2022-06-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private EmailUtil emailUtil;

    @GetMapping("/getUser/{userId}")
    public R getUser(@PathVariable String userId){
        User user = iUserService.getUser(userId);
        return R.ok().data("user",user);
    }

    /**
     * 登录
     * @param userEmail
     * @param password
     * @return
     */
    @GetMapping("whlogin/{userEmail}/{password}")
    private R whlogin(@PathVariable("userEmail") String userEmail, @PathVariable("password") String password){

        password = MD5.encrypt(password);

        return iUserService.whlogin(userEmail,password);
    }

    /**
     * 注册
     * @param userEmail
     * @param password
     * @return
     */
    @GetMapping("register/{userEmail}/{password}")
    private R register(@PathVariable("userEmail") String userEmail, @PathVariable("password") String password){

        password = MD5.encrypt(password);

        System.out.println(userEmail+"++++++++++++"+password);

        return iUserService.register(userEmail,password);
    }

    /**
     *  验证码
     * @param userEmail

     * @return
     */
    @GetMapping("verificationCode/{userEmail}")
    private R verificationCode(@PathVariable("userEmail") String userEmail){
        String verificationCode = String.valueOf(new Random().nextInt(899999) + 100000);
        emailUtil.sendSimpleMail(userEmail,"验证码",verificationCode);
        System.out.println("发送成功");
        return R.ok().data("verificationCode", verificationCode);
    }

    /**
     * 忘记密码
     * @param userEmail
     * @param password
     * @return
     */
    @GetMapping("forgot/{userEmail}/{password}")
    private R forgot(@PathVariable("userEmail") String userEmail, @PathVariable("password") String password){
        return iUserService.forgot(userEmail, password);
    }
    Logger log= LogManager.getLogger();





    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/getUserLogin")
    @ApiOperation(value = "app用户登录")
    public R login(String phone,String password){

        User user = iUserService.login(phone,password);
        System.out.println("-------------"+user);
        if (user != null){
            return R.ok().message("登陆成功").data("userVo",user);
        }else {
            return R.error().message("登录失败，用户名或密码错误");
        }
    }

    @PostMapping("/getCheckCode/{email}")
    @ApiOperation(value = "app用户注册发送验证码")
    public R getCheckCode(@PathVariable String email){


        log.info("发送的邮箱为==============="+email);
        String checkCode = String.valueOf((int)((Math.random()*9+1)*100000));
        log.info("验证码为==================="+checkCode);

        if (checkCode!=""){
            redisUtil.set(email, checkCode, 180);
            String message = "您的注册验证码为："+checkCode +"有效时长3分钟";
            emailUtil.sendSimpleMail(email, "注册验证码", message);
            return R.ok().message("邮件发送成功，请查收邮件");
        }
        else {
            return R.error().message("发送失败,无此邮箱");
        }
    }

    @PostMapping("/registerInfo")
    @ApiOperation(value = "app用户注册")
    public R registerInfo(@RequestBody User user){

        System.out.println("---------------"+user.toString());

        String sss = redisUtil.get(user.getEmail()).toString();
        System.out.println("-------------"+sss);
        int a=iUserService.selectEmail(user.getEmail());

        if (a==0){
            if (sss.equals(user.getGraphicVerifyCode())){

                iUserService.registerInfo(user);
                return R.ok().message("注册成功");
            }else {
                return R.error().message("注册失败，信息有误或者验证码失效");
            }

        }else {
            return R.error().message("邮箱已存在");
        }
    }

    @PostMapping("/updatePwd")
    @ApiOperation(value = "app用户修改密码")
    public R updatePwd(@RequestBody User user){

        System.out.println("---------------"+user.toString());


        int a=iUserService.selectEmail(user.getEmail());

        if (a==1){
            String sss = redisUtil.get(user.getEmail()).toString();
            System.out.println("-------------"+sss);
            if (sss.equals(user.getGraphicVerifyCode())){

                iUserService.updatePwd(user);
                return R.ok().message("修改成功");
            }else {
                return R.error().message("修改失败，信息有误或者验证码失效");
            }

        }else {
            return R.error().message("邮箱不存在");
        }
    }

    @PostMapping("/appUserInfo")
    @ApiOperation(value = "app我的房屋(住户信息添加)")
    public R appUserInfo(@RequestBody UserFile userFile){

        System.out.println("++++++"+userFile.toString());



            String sss = redisUtil.get(userFile.getEmail()).toString();


            System.out.println("-------------"+sss);

            if (sss.equals(userFile.getGraphicVerifyCode())){

                iUserService.appUserInfo(userFile);
                return R.ok().message("修改成功");
            }else {
                return R.error().message("修改失败，信息有误或者验证码失效");
            }

        }



    /**
     * 住户全查
     * @return
     */
    @GetMapping("/findResidents")
    public R findResidents(){
        return iUserService.findResidents("","");
    }

    /**
     * 删除住户
     * @param id
     * @return
     */
    @GetMapping("/delResidents/{id}")
    public R delResidents(@PathVariable("id") Integer id){
        return iUserService.delResidents(id);
    }

    @GetMapping("/findIdResidents/{type}/{name}")
    public R findIdResidents(@PathVariable String type,@PathVariable String name){
        return iUserService.findResidents(type,name);
    }

    @GetMapping("/countWorkbench")
    public R countWorkbench(){
        return iUserService.countWorkbench();
    }

    @PostMapping("/updateResident")
    public R updateResident(@RequestBody Residents residents){
        return iUserService.updateResident(residents);
    }

    @GetMapping("/auditResident/{userId}/{audit}")
    public R auditResident(@PathVariable Integer userId,@PathVariable String audit){

        System.out.println(userId+"=============================="+audit);

        return iUserService.auditResident(userId,audit);
    }

}
